﻿using System;
using MessageSystem.Managed.Infrastructure;

namespace MessageSystem.Managed.Serialization
{
    public class UnknownField
    {
        public static void Read(NetStream ns)
        {
            UInt16 nFieldIndex;
            MessageFieldType nFieldType;
            MessageFieldTag.ReadTag(out nFieldIndex, out nFieldType, ns);
            Read(nFieldType, ns);
        }

        public static void Read(MessageFieldType nFieldType, NetStream ns)
        {
            switch (nFieldType)
            {
                case MessageFieldType.Int8:
                    {
                        ns.ReadByte();
                        break;
                    }
                case MessageFieldType.Int16:
                    {
                        ns.ReadInt16();
                        break;
                    }
                case MessageFieldType.Int32:
                    {
                        ns.ReadInt32();
                        break;
                    }
                case MessageFieldType.Int64:
                    {
                        ns.ReadInt64();
                        break;
                    }
                case MessageFieldType.String:
                    {
                        string s = ns.ReadString();
                        break;
                    }
                case MessageFieldType.List:
                    {
                        int length = ns.ReadUInt16();
                        MessageFieldType nInnerFieldType = (MessageFieldType)ns.ReadByte();
                        while (length-- > 0)
                        {
                            Read(nInnerFieldType, ns);
                            if (length > 0 && nInnerFieldType == MessageFieldType.ObjectStart)
                                nInnerFieldType = (MessageFieldType)ns.ReadByte();
                        }                         
                        break;
                    }
                case MessageFieldType.ObjectStart:
                    {
                        UInt16 nInnerFieldIndex;
                        MessageFieldType nInnerFieldType;
                        MessageFieldTag.ReadTag(out nInnerFieldIndex, out nInnerFieldType, ns);

                        while (nInnerFieldType != MessageFieldType.ObjectEnd)
                        {
                            Read(nInnerFieldType, ns);

                            MessageFieldTag.ReadTag(out nInnerFieldIndex, out nInnerFieldType, ns);
                        }
                        break;
                    }
                case MessageFieldType.ObjectEnd:
                    {
                        break;
                    }
            }
        }
    }
}
